package cn.mybatishelper.ui.listener;

import cn.mybatishelper.builder.DefaultHandlerBuilder;
import cn.mybatishelper.common.BaseInfoConstants;
import cn.mybatishelper.director.BuilderDirector;
import cn.mybatishelper.ui.uienum.MybatiesInfoEnum;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * mybaties初始化信息的确定按钮监听类
 * 负责对参数的校验和将程序转向执行操作
 * User: GameKing
 * Date: 15-8-21
 * Time: 上午10:52
 */
public class MyBatisInfoListener implements ActionListener {
    private JPanel panel;
    private JList jList;

    public MyBatisInfoListener(JList jList, JPanel panel) {
        this.jList = jList;
        this.panel = panel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        /**
         * 处理初始化参数
         */
        Component[] components = panel.getComponents();
        for (Component component : components) {
            if (!(component instanceof JTextField)) {
                continue;
            }
            JTextField jTextField = (JTextField) component;
            if (!validateJTextField(jTextField)) {
                JOptionPane.showMessageDialog(null, MybatiesInfoEnum.getNameByValue(jTextField.getName()) + " 不能为空", "提示", JOptionPane.ERROR_MESSAGE);
                return;
            }
            setValue(jTextField.getName(), jTextField.getText());
        }

        /**
         * 开始处理选中的表
         */
        Object[] objs = jList.getSelectedValues();
        if (ArrayUtils.isEmpty(objs)) {
            JOptionPane.showMessageDialog(null, "最少要选择一张表", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        handleTables(objs);

        Thread thread = createAndRun();
        JOptionPane.showMessageDialog(null, "正在后台生成文件，请稍候", "提示", JOptionPane.INFORMATION_MESSAGE);
        try {
            thread.join();
            JOptionPane.showMessageDialog(null, "生成操作执行完毕", "提示", JOptionPane.OK_OPTION);
        } catch (InterruptedException e1) {
            JOptionPane.showMessageDialog(null, "生成失败，请查看日志", "提示", JOptionPane.ERROR_MESSAGE);
        }
        System.exit(0);
    }

    /**
     * 启用新线程来执行具体的生成操作
     */
    private Thread createAndRun() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                DefaultHandlerBuilder builder = new DefaultHandlerBuilder();
                BuilderDirector director = new BuilderDirector(builder);
                director.construct();
                builder.execute();
            }
        });
        thread.run();
        return thread;
    }

    /**
     * 对选中的表信息进行处理
     *
     * @param objs
     */
    private void handleTables(Object[] objs) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < objs.length; i++) {
            stringBuilder.append(String.valueOf(objs[i]));
            if ((i + 1) < objs.length) {
                stringBuilder.append(",");
            }
        }
        BaseInfoConstants.tableNames = stringBuilder.toString();
    }

    /**
     * 对表单输入进行验证，只有舍弃字段和分隔字段允许为空
     */
    private boolean validateJTextField(JTextField jTextField) {
        if (StringUtils.isNotBlank(jTextField.getText())) {
            return true;
        }
        if (MybatiesInfoEnum.TABLE_NAME_REMOVE.getValue().equals(jTextField.getName())) {
            return true;
        }
        if (MybatiesInfoEnum.TABLE_NAME_SEPARATE.getValue().equals(jTextField.getName())) {
            return true;
        }
        if (MybatiesInfoEnum.MAPPER_EXTEND_URL.getValue().equals(jTextField.getName())) {
            return true;
        }
        return false;
    }

    /**
     * 将表单的值赋给全局静态化变量
     */
    private void setValue(String name, String value) {
        if (name.equals(MybatiesInfoEnum.ROOT_DIR.getValue())) {
            BaseInfoConstants.rootDir = value;
        }
        if (name.equals(MybatiesInfoEnum.MAPPER_PACKAGE.getValue())) {
            BaseInfoConstants.mapperPackage = value;
        }
        if (name.equals(MybatiesInfoEnum.PERSISTENCE_PACKAGE.getValue())) {
            BaseInfoConstants.poPackage = value;
        }
        if (name.equals(MybatiesInfoEnum.TABLE_NAME_REMOVE.getValue())) {
            BaseInfoConstants.tableNameRemove = value;
        }
        if (name.equals(MybatiesInfoEnum.TABLE_NAME_SEPARATE.getValue())) {
            BaseInfoConstants.tableNameSeparate = value;
        }
        if (name.equals(MybatiesInfoEnum.MAPPER_EXTEND_URL.getValue())) {
            BaseInfoConstants.mapperExtendJavaUrl = value;
        }
    }
}
